package com.eastdigit.bpm.formType;

import java.util.LinkedHashMap;
import java.util.Map;

import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.FormValue;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.form.AbstractFormType;
import org.activiti.engine.impl.form.BooleanFormType;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.DoubleFormType;
import org.activiti.engine.impl.form.FormTypes;
import org.activiti.engine.impl.form.LongFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.apache.commons.lang3.StringUtils;

public class ExtendFormTypes extends FormTypes{
    
    public ExtendFormTypes(){
        this.addFormType(new StringFormType());
        this.addFormType(new LongFormType());
        this.addFormType(new DateFormType("dd/MM/yyyy"));
        this.addFormType(new BooleanFormType());
        this.addFormType(new DoubleFormType());
    }


    @Override
    public AbstractFormType parseFormPropertyType(FormProperty formProperty) {
        AbstractFormType formType = null;

        if ("date".equals(formProperty.getType()) && StringUtils.isNotEmpty(formProperty.getDatePattern())) {
          formType = new DateFormType(formProperty.getDatePattern());
          
        } else if ("enum".equals(formProperty.getType())) {
          // ACT-1023: Using linked hashmap to preserve the order in which the entries are defined
          Map<String, String> values = new LinkedHashMap<String, String>();
          for (FormValue formValue: formProperty.getFormValues()) {
            values.put(formValue.getId(), formValue.getName());
          }
          //formType = new EnumFormType(values);
          formType = new MyEnumFormType(values);
          
        } else if (StringUtils.isNotEmpty(formProperty.getType())) {
          formType = formTypes.get(formProperty.getType());
          if (formType == null) {
                if (formProperty.getType().startsWith("code:")) {
                    String codetype = formProperty.getType().substring(5);
                    if (StringUtils.isNotEmpty(codetype)) {
                        formType = new CodeFormType(codetype);
                    }
                }
              if(formType == null){
                  throw new ActivitiIllegalArgumentException("unknown type '" + formProperty.getType() + "' " + formProperty.getId());
              }
          }
        }
        return formType;
    }
    
}
